import React, { useState, useEffect } from 'react';
import { forgetLoginPwd, getPhoneNumberOp, getCaptchaImage, getSaftCaptchaOp } from './service';
import { useNavigate } from 'react-router-dom';
import { mobile, passWord } from '@/utils/rule';
import { getCode } from '@/services/user';
import CommonLoading from '@/components/CommonLoading';
import { Form, Input, Button, Row, Col, Select, Popover, message, notification } from 'antd';
import { UserOutlined, LockOutlined, MailTwoTone } from '@ant-design/icons';

import styles from './index.module.less';

const { Option } = Select;

export default () => {

  const [ form ] = Form.useForm();
  const [ loading, setLoading ] = useState(false);
	const navigate = useNavigate();
  const onFinish = async val => {
    const { pwd, mobile, smsCode } = val;
    setLoading(true);
    const res = await forgetLoginPwd({ pwd, mobile, smsCode, tenantId: '000000', appCode: 'ERP', industrialBeltFlag: INDUSTRIAL_BELT_FLAG });
    setLoading(false);
    if(res.success) {
      message.success('重置成功，即将跳转到登录页面');
      navigate('/user/login');
    }
  };

  const [ count, setCount ] = useState(0);
  const [captchaObj, setObj] = useState({});

	const { image: imgCaptcha, key } = captchaObj;

  useEffect(()=>{
		if(count){
		 setTimeout(()=>{
			 setCount(count-1);
		 }, 1000)
		}
	 },[count])

  useEffect(()=>{
		if(imgCaptcha){
		 form.validateFields(['Captcha-Code'])
		}
	},[imgCaptcha])

  const prefixSelector = (
    <Form.Item name="prefix"  noStyle>
      <Select style={{ width: 80 }} size='large'>
        <Option value="86">+86</Option>
        <Option value="87">+87</Option>
      </Select>
    </Form.Item>
  );

  const handleGetCode = async (val) => {
    const { data, success } = await getCode({
      mobile: val,
      type: '3',
      industrialBeltFlag: INDUSTRIAL_BELT_FLAG
    })
    if (success) {
		  if(data){
        message.success('验证码发送成功！');
        setCount(59);
      }else{
        getImgCaptchaFunc(true);
      }
		}
  }

  const getImgCaptchaFunc = async (bool) => {
		const res = await getCaptchaImage();
    if(res?.key && bool){
      notification.info({
        message: `温馨提示`,
        description: '鉴于安全因素，请输入图形验证码，验证通过后方可重新获取手机验证码',
      });   
      setObj(res);
    }
 }

  const onGetCaptcha = async () => {
    if(imgCaptcha){
      form.validateFields([ 'Captcha-Code', 'mobile' ]).then(val=>{
        getSaftCaptchaFunc(val);
      })
    }else{
      form.validateFields([ 'mobile' ])
      .then(values => {
        handleGetCode(values.mobile);
      })
    }
  }

  //通过账号名获取手机号
  const getPhoneNumber = async (e) => {
    const value = e.target.value;
    if(!value) {
      return;
    }
    setLoading(true);
    const { success, data } = await getPhoneNumberOp({ account: value });
    if(success && data) {
      form.setFieldsValue({
        mobile: data.phone
      })
    }
    setLoading(false);
  }

  const getSaftCaptchaFunc = async (val) => {
    const { success } = await getSaftCaptchaOp({
      ...val,
      type: '3',
      appType: '2',
      industrialBeltFlag: INDUSTRIAL_BELT_FLAG,
      'Captcha-Key': key, 
    });
    if(success){
      message.success('验证码发送成功！');
      setCount(59);
      setObj({});
    }else{
      getImgCaptchaFunc();
      form.setFieldsValue({
        'Captcha-Code': null,
        'smsCode': null
      })
    }
  }

  return (
    <>
      <div className={styles.main}>
        <h3 style={{ textAlign: 'center', marginBottom: '12px' }}>重置密码</h3>
        <Form
          name='forget-password'
          onFinish={onFinish}
          form={form}
          style={{ width: '100%' }}
          initialValues={{
            prefix: '86',
            tenantId: '000000'
          }}
        >
          {/* <Form.Item
            name="tenantId"
            rules={[{ required: true, message: '请输入租户id' }]}
          >
            <Input size="large" prefix={<HomeOutlined className={styles.prefixIcon} />} placeholder="租户id：000000" />
          </Form.Item> */}
             <Form.Item
            name="account"
            validateTrigger="onBlur"
            validateFirst
          >
            <Input size="large" prefix={<UserOutlined className={styles.prefixIcon} />} onBlur={getPhoneNumber} placeholder="请输入账号名,限制18个字符" />
          </Form.Item>

          <Form.Item
            name="mobile"
            rules={[
              { required: true, message: '请输入手机号' },
              mobile
            ]}
          >
            <Input size='large' addonBefore={prefixSelector} />
          </Form.Item>
          {
            imgCaptcha && <Row gutter={8}>
            <Col span={16}>
              <Form.Item
                name="Captcha-Code"
                rules={[
                  { required: true, message: '请输入验证码' },
                  { pattern: /^[A-Za-z0-9]+$/, message: '输入格式有误' },
                ]}
              >
                <Input size="large" prefix={<MailTwoTone className={styles.prefixIcon} />} placeholder="请输入验证码！" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <img alt="captcha" src={imgCaptcha} className={styles.getImgCaptcha} onClick={getImgCaptchaFunc} />
            </Col>
          </Row>
          }
          <Row gutter={8}>
            <Col span={16}>
              <Form.Item 
                name="smsCode" 
                rules={[{ required: true, message: '请输入验证码' }]}
              >
                <Input size="large" prefix={<MailTwoTone className={styles.prefixIcon} />} placeholder="请输入验证码！" />
              </Form.Item>
            </Col>
            <Col span={8} style={{ textAlign: 'right' }}>
              <Button disabled={count} style={{ width: '100%', fontSize: '14px', padding: 0 }} onClick={onGetCaptcha} size='large'>{ count ? `${count}s` : '获取验证码'}</Button>
            </Col>
          </Row>

          <Popover  content={
           <div style={{ width: '240px' }}>
             <p style={{ marginBottom: '12px' }}>1、密码至少为8位，且必须包含大小写字母、数字和特殊字符三种</p>
             <p>2、特殊字符支持的有：{`!，@，#，$，%，^，&`}</p>
           </div> 
          } trigger={['click']}  placement="right">
            <Form.Item
              name="pwd"
              validateFirst
              rules={[
                { required: true, message: '请输入新密码' },
                {
                  pattern: /^[^\s]*$/,
                  message: '不能包含空格',
                },
                {
                  pattern: /^[^\u4e00-\u9fa5]{1,}$/g,
                  message: '不支持中文',
                },
                passWord,
              ]}
            >
              <Input
                prefix={<LockOutlined className={styles.prefixIcon} />}
                type="password"
                size="large"
                placeholder="请输入新密码"
                autoComplete="new-password" 
              />
            </Form.Item>
          </Popover>
          <Form.Item
            name="confirm"
            dependencies={['pwd']}
            rules={[
              { required: true, message: '请确认新密码' },
              ({ getFieldValue }) => ({
                validator(rule, value) {
                  if (!value || getFieldValue('pwd') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject('两次输入密码不一致');
                },
              }),
            ]}
          >
            <Input
              // prefix={<LockOutlined className={styles.prefixIcon} />}
              type="password"
              size="large"
              placeholder="请确认新密码"
            />
          </Form.Item>
   
          <Form.Item >
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <Button type='primary' htmlType='submit' size='large' style={{ width: '100%' }}>确定重置</Button>
            </div>
          </Form.Item>
        </Form>
      </div>
      <CommonLoading loading={loading} />
    </>
  )
}